package com.infra.micro.id.domain.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.infra.common.resp.PageEx;
import com.infra.common.resp.Response;
import com.infra.micro.id.domain.cache.AppCache;
import com.infra.micro.id.domain.core.segment.IdSegmentGenerator;
import com.infra.micro.id.domain.entity.IdSegmentPO;
import com.infra.micro.id.domain.repository.IdSegmentRepository;
import com.infra.micro.id.domain.service.IdSegmentService;
import com.infra.micro.id.model.req.QueryIdSegmentByCondReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class IdSegmentServiceImpl extends IdSegmentGenerator implements IdSegmentService {
    private final AppCache appCache;

    public IdSegmentServiceImpl(IdSegmentRepository idSegmentRepository, AppCache appCache) {
        super(idSegmentRepository);
        this.appCache = appCache;
    }

    @Override
    public Long getId(Integer appId, String secretKey) {
        if (bizConfig.getEnableAuth() && !appCache.verify(appId.toString(), secretKey)) {
            throw new IllegalArgumentException("请提供正确的密钥");
        }
        return super.getId(appId);
    }

    @Override
    public Set<Long> getIds(Integer appId, int step, String secretKey) {
        if (bizConfig.getEnableAuth() && !appCache.verify(appId.toString(), secretKey)) {
            throw new IllegalArgumentException("请提供正确的密钥");
        }
        return super.getIds(appId, step);
    }

    @Override
    public Response<PageEx<IdSegmentPO, QueryIdSegmentByCondReq>> list(QueryIdSegmentByCondReq req) {
        PageInfo<IdSegmentPO> pageInfo = PageHelper.startPage(req.getPageIndex(), req.getPageSize(), StringUtils.isEmpty(req.getSortField()) ? "segment_id asc" : req.getSortField() + " " + req.getSortType())
                .doSelectPageInfo(() -> idSegmentRepository.queryByCond(req));

        return Response.success(PageEx.builder(pageInfo, req), "查询成功");
    }

    public Response<Integer> update(Long segmentId, IdSegmentPO record) {
        if (segmentId == null || segmentId.equals(0)) {
            return Response.error("无效参数！");
        }
        record.setSegmentId(segmentId);
        return Response.success(idSegmentRepository.update(record), "更新成功");
    }
}
